package com.hefan.common.util;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;

public class HttpUtils {


    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);


    public static String getParam(HttpServletRequest req, String paramName, String def) {
        String ret = req.getParameter(paramName);
        if (StringUtils.isEmpty(ret)) {
            ret = def;
        }
        return ret;
    }

    public static Date getParamAsDate(HttpServletRequest req, String paramName, SimpleDateFormat sdf, Date def) {
        try {
            return sdf.parse(req.getParameter(paramName).trim());
        } catch (Exception e) {
            return def;
        }
    }

    public static float getParamAsFloat(HttpServletRequest req, String paramName, float def) {
        try {
            return Float.parseFloat(req.getParameter(paramName).trim());
        } catch (Exception e) {
            return def;
        }
    }

    public static int getParamAsInt(HttpServletRequest req, String paramName, int def) {
        try {
            return Integer.parseInt(req.getParameter(paramName).trim());
        } catch (Exception e) {
            return def;
        }
    }

    public static long getParamAsLong(HttpServletRequest req, String paramName, long def) {
        try {
            return Long.parseLong(req.getParameter(paramName).trim());
        } catch (Exception e) {
            return def;
        }
    }

    public static String getReferer(HttpServletRequest req) {
        String referer = req.getHeader("referer");
        if (referer != null) {
            return referer;
        } else {
            return req.getHeader("Referer");
        }
    }

    public static <T> T initParam(HttpServletRequest req, Class<T> clazz) {
        try {
            String paramStr = HttpUtils.getParam(req, "data", null);
            if (StringUtils.isBlank(paramStr))
                return null;
            return JSON.parseObject(paramStr, clazz);
        } catch (Exception ex) {
            return null;
        }
    }


    public static String getRequestUrl(String uri, String queryString) {
        String url = uri;
        if (StringUtils.isNotBlank(queryString)) {
            url = url + "?" + queryString;
        }
        return url;
    }

    public static String getUserAgent(HttpServletRequest request) {
        String ua = "";
        if (StringUtils.isNotBlank(request.getHeader("user-agent"))) {
            ua = request.getHeader("user-agent");
        } else if (StringUtils.isNotBlank(request.getHeader("User-Agent"))) {
            ua = request.getHeader("User-Agent");
        } else if (StringUtils.isNotBlank(request.getHeader("user-Agent"))) {
            ua = request.getHeader("user-Agent");
        }
        return ua;
    }


    public static JSONObject getJSONObjectByRequestUrl(String url) {
        BufferedReader reader = null;
        if (StringUtils.isNotBlank(url)) {

            try {
                HttpClient client = new DefaultHttpClient();
                HttpGet getRequest = new HttpGet(url);
                getRequest.addHeader("Content-Type", "application/json");
                getRequest.addHeader("charset", HTTP.UTF_8);

                HttpResponse responce = client.execute(getRequest);
                StatusLine statusLine = responce.getStatusLine();
                int statusCode = statusLine.getStatusCode();

                if (statusCode != 200) {
                    logger.error("statusCode==>" + statusCode);
                    return null;
                }

                InputStream jsonStream = responce.getEntity().getContent();
                reader = new BufferedReader(new InputStreamReader(jsonStream));
                StringBuilder builder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }

                String jsonData = builder.toString();

                JSONObject json = new JSONObject(jsonData);

                return json;


            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                    }
                }
            }
        }

        return null;
    }

    /**
     * 获取参数
     *
     * @param request
     * @param name
     * @return
     */
    public static String reqHeader(HttpServletRequest request, String name) {
        String param = request.getHeader(name);
        return param == null ? "" : param;
    }

    /**
     * 获取header信息中的埋点对象
     * @param request
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T reqBuriedPointHeader(HttpServletRequest request, Class<T> clazz) {
        try {
            String jsonStr = reqHeader(request, "buriedPoint");
            if (!StringUtils.isBlank(jsonStr)) {
                return JSON.parseObject(jsonStr, clazz);
            }
        }catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }

}
